//
//  JNCardSDKResetPauseVC.m
//  IDCardManager
//
//  Created by 金牛 on 2017/12/5.
//  Copyright © 2017年 zou. All rights reserved.
//

#import "JNCardSDKResetPauseVC.h"
#import "FSCalendar.h"
@interface JNCardSDKResetPauseVC ()<FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance >
{
    UILabel *_hasChoseDateLab,*_adviceChoseLab/*建议计划天数lab*/;
    NSString * _billDateStr, * _payDateStr;
    NSMutableArray * _dateList ;
    NSInteger _minDays,_maxDays,_choseCount;
}
@end

@implementation JNCardSDKResetPauseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTitle = @"重启计划";
    _dateList = [NSMutableArray new];
    NSMutableDictionary * dic = [JNCardSDKCalculaterBillPayDay getBillDateAndPayDate:self.model.billDate andPayDay:self.model.dueDate];
    _billDateStr = dic[@"finalBillDay"];
    _payDateStr = dic[@"finalPayDay"];
    [self createUI];
    [self getResetPlanDays];
}
-(void)createUI{
    UIView * bgView = [UIView new];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    bgView.sd_layout.leftEqualToView(self.view).rightEqualToView(self.view).topSpaceToView(self.view, kTopHeight);
    UILabel * descLab = [UILabel labelWithTitle:@"已超过自助重启时间，若继续重启，需重新选择执行时间，且会对剩余未执行之计划进行重组" color:[UIColor blackColor] fontSize:14];
    descLab.textAlignment = NSTextAlignmentLeft;
    [bgView addSubview:descLab];
    descLab.sd_layout.leftSpaceToView(bgView, 10).rightSpaceToView(bgView, 10).topSpaceToView(bgView, 20).autoHeightRatio(0);
    
    UIView * hLineView = [UIView new];
    hLineView.backgroundColor = [UIColor lightGrayColor];
    [bgView addSubview:hLineView];
    hLineView.sd_layout.leftEqualToView(descLab).rightEqualToView(descLab).topSpaceToView(descLab, 20).heightIs(1);
    
    UILabel * setTitleLab = [UILabel labelWithTitle:@"请设置计划时间" color:[UIColor blackColor] fontSize:14];
    [bgView addSubview:setTitleLab];
    setTitleLab.sd_layout.leftEqualToView(hLineView).topSpaceToView(hLineView, 20).heightIs(16);
    [setTitleLab setSingleLineAutoResizeWithMaxWidth:200];
    
    _adviceChoseLab = [UILabel labelWithTitle:@"" color:[UIColor blackColor] fontSize:14];
    [bgView addSubview:_adviceChoseLab];
    _adviceChoseLab.sd_layout.rightSpaceToView(bgView, 5).centerYEqualToView(setTitleLab).heightIs(16);
    [_adviceChoseLab setSingleLineAutoResizeWithMaxWidth:200];
    
    UILabel * tmplAas = [UILabel labelWithTitle:@"已选择日期" color:[UIColor blackColor] fontSize:14];
    [bgView addSubview:tmplAas];
    tmplAas.sd_layout.leftEqualToView(setTitleLab).topSpaceToView(setTitleLab, 10).heightIs(16);
    [tmplAas setSingleLineAutoResizeWithMaxWidth:200];
    
    _hasChoseDateLab = [UILabel labelWithTitle:@"" color:[UIColor blackColor] fontSize:14];
    [bgView addSubview:_hasChoseDateLab];
    _hasChoseDateLab.sd_layout.leftEqualToView(tmplAas).topSpaceToView(tmplAas, 10).heightIs(16);
    [_hasChoseDateLab setSingleLineAutoResizeWithMaxWidth:IPHONE_WIDTH-20];
    
    FSCalendar *calendar = [[FSCalendar alloc] init];
    calendar.dataSource = self;
    calendar.delegate = self;
    calendar.appearance.todayColor = [UIColor clearColor];
    //                calendar.
    calendar.allowsMultipleSelection = YES;
    [bgView addSubview:calendar];
    calendar.sd_layout.leftEqualToView(bgView).rightEqualToView(bgView).topSpaceToView(_hasChoseDateLab, 10).heightIs(300);
    
    [bgView setupAutoHeightWithBottomView:calendar bottomMargin:10];
    
    UIButton * submitBtn = [UIButton new];
    submitBtn.backgroundColor = ThemeColor;
    [submitBtn setTitle:@"确定，重启计划" forState:0];
    [submitBtn addTarget:self action:@selector(resetPlanTime) forControlEvents:UIControlEventTouchUpInside];
    submitBtn.layer.masksToBounds = YES;
    submitBtn.layer.cornerRadius = 5;
    [self.view addSubview:submitBtn];
    submitBtn.sd_layout.leftSpaceToView(self.view, 20).rightSpaceToView(self.view, 20).bottomSpaceToView(self.view, 20).heightIs(40);
}
-(BOOL)isOutFourClock{
    NSDate * todayDate = [JNCardSDKMytools getCurrentDate];//当天日期
    NSDate * fourClockDate = [JNCardSDKMytools dateStrToDate:self.pausePlanStr];
    if ([JNCardSDKMytools compareOneDay:todayDate withAnotherDay:fourClockDate]==1) {
        return NO;
    }else{
        return YES;
    }
}
-(void)getResetPlanDays{
    //根据后台返回的获取可选天数
    NSMutableDictionary * p = [JNCardSDKReuserFile returnHYKBaseDic];
    [p setObject:self.planID forKey:@"PlanId"];
    NSString * url = [JNCardSDKWorkUrl returnURL:Interface_For_GetResetPlanDay];
    [PGNetworkHelper POST:url parameters:p cache:NO responseCache:nil success:^(id responseObject) {
        if ([responseObject[@"status"]isEqualToString:@"1"]) {
            self->_minDays = ceilf([responseObject[@"data"][@"minday"] doubleValue]);
            self->_maxDays = [responseObject[@"data"][@"maxday"] integerValue];
            self->_adviceChoseLab.text = [NSString stringWithFormat:@"建议天数：%ld-%ld天",self->_minDays,self->_maxDays];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark 日历代理

- (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{

    date = [date dateByAddingTimeInterval:8 * 60 * 60];
    BOOL reg = [JNCardSDKCalculaterBillPayDay holidayListCanChose:date isFromSelect:YES];
    if (reg == NO) {
        return NO;
    }
    if ([self isOutFourClock]==YES) {
        return NO;
    }
    
    if (_choseCount>_maxDays) {
        [JNCardSDKMytools warnText:@"选择天数超出最大可选天数" status:JNCardSDKError];
        return NO;
    }
    
    NSDate * billDate = [JNCardSDKMytools dateStrToDate:_billDateStr];
    NSDate * payDate = [JNCardSDKMytools dateStrToDate:_payDateStr];
    NSDate * todayDate = [JNCardSDKMytools getCurrentDate];//当天日期
    NSString * todayStr = [JNCardSDKMytools dateToDateStr:todayDate];
    todayStr = [todayStr stringByReplacingCharactersInRange:NSMakeRange(11, 8) withString:@"00:00:00"];
    todayDate = [JNCardSDKMytools dateStrToDate:todayStr];
    
    JNCardSDKVicSingleObject * single = [JNCardSDKVicSingleObject getInstance];
    NSInteger pos1 = single.dayStatus==1?1:single.beforeDay;
    NSInteger pos2 = single.dayStatus==1?1:single.beforeHour;
    if (single.beforeDay==0) {
        pos1 = 1;
        pos2 = single.beforeHour==0?1:single.beforeHour;
    }else if (single.beforeHour == 0){
        pos1 = single.beforeDay==0?1:single.beforeDay;
        pos2 = 24;
    }
    NSTimeInterval time = pos1 * pos2 * 60 * 59;//计算给定后的日期
    NSDate * twoDayDate = [NSDate dateWithTimeInterval:time sinceDate:todayDate];//时间间隔
    NSDate * twoDayBeforePayDate = [NSDate dateWithTimeInterval:-(time+24*60*59) sinceDate:payDate];//还款日的前single.beforeDay+1天
    NSDate * twoDayAfterBillDate = [NSDate dateWithTimeInterval:time sinceDate:billDate];//账单日的后single.beforeDay天
    
    if ([[_billDateStr substringWithRange:NSMakeRange(8, 2)] intValue]<[[_payDateStr substringWithRange:NSMakeRange(8, 2)] intValue]) {
        //当月
        if([JNCardSDKMytools compareOneDay:date withAnotherDay:twoDayDate]==1&&[JNCardSDKMytools compareOneDay:twoDayBeforePayDate withAnotherDay:date]==1){
            //日历的日期大于当天日期且小于还款日期，可选
            return YES;
        }else{//不可选
            return NO;
        }
    }else{
        //跨月
        if ([JNCardSDKMytools compareOneDay:twoDayDate withAnotherDay:twoDayAfterBillDate]==1) {
            //表示在未跨的那个月，比如账单日7月25，当天7月28，还款8月9
            if ([JNCardSDKMytools compareOneDay:date withAnotherDay:twoDayDate]==1&&[JNCardSDKMytools compareOneDay:twoDayBeforePayDate withAnotherDay:date]==1) {
                return YES;
            }else{
                return NO;
            }
        }else{
            if ([JNCardSDKMytools compareOneDay:date withAnotherDay:twoDayBeforePayDate]==1) {
                return NO;
            }else{
                //因为账单在这个页面一定存在，所以除去上面的那个情况，当天日期一定在8月9之前7月31之后，要做的就是限制8月9之后显示为黑色的bug
                NSInteger  tmpMonth = [[JNCardSDKCalculaterBillPayDay getTheCorrectNum:[_payDateStr substringWithRange:NSMakeRange(5, 2)]] intValue];
                if (tmpMonth == 1) {
                    tmpMonth = 12;
                }else{
                    tmpMonth = tmpMonth - 1;
                }
                NSString * tmpMonthStr = [NSString stringWithFormat:@"%ld",tmpMonth];
                NSString * newPayDateStr = [_payDateStr stringByReplacingCharactersInRange:NSMakeRange(5, 2) withString:tmpMonthStr];
                NSDate * newPayDate  = [JNCardSDKMytools dateStrToDate:newPayDateStr];
                NSDate * twoDayBeforNewPayDate = [NSDate dateWithTimeInterval:-time sinceDate:newPayDate];
                
                if ([[_billDateStr substringWithRange:NSMakeRange(8, 2)] intValue]<[[_payDateStr substringWithRange:NSMakeRange(8, 2)] intValue]) {
                    if ([JNCardSDKMytools compareOneDay:date withAnotherDay:twoDayDate]==1&&[JNCardSDKMytools compareOneDay:twoDayBeforNewPayDate withAnotherDay:date]==1) {
                        return YES;
                    }else{
                        return NO;
                    }
                }else{
                    return NO;
                }
            }
        }
    }
}

//返回可选范围和不可选范围的颜色
- (nullable UIColor *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance titleDefaultColorForDate:(NSDate *)date{
    
    if ([self isOutFourClock]==YES) {
        return [UIColor colorWithHue:0 saturation:0 brightness:0.67 alpha:1];
    }
    
    date = [date dateByAddingTimeInterval:8 * 60 * 60];
    BOOL reg = [JNCardSDKCalculaterBillPayDay holidayListCanChose:date isFromSelect:NO];
    if (reg == NO) {
        return [UIColor colorWithHue:0 saturation:0 brightness:0.67 alpha:1];
    }
    NSDate * billDate = [JNCardSDKMytools dateStrToDate:_billDateStr];
    NSDate * payDate = [JNCardSDKMytools dateStrToDate:_payDateStr];
    NSDate * todayDate = [JNCardSDKMytools getCurrentDate];//当天日期
    NSString * todayStr = [JNCardSDKMytools dateToDateStr:todayDate];
    todayStr = [todayStr stringByReplacingCharactersInRange:NSMakeRange(11, 8) withString:@"00:00:00"];
    todayDate = [JNCardSDKMytools dateStrToDate:todayStr];
    
    
    JNCardSDKVicSingleObject * single = [JNCardSDKVicSingleObject getInstance];
    NSInteger pos1 = single.dayStatus==1?1:single.beforeDay;
    NSInteger pos2 = single.dayStatus==1?1:single.beforeHour;
    if (single.beforeDay==0) {
        pos1 = 1;
        pos2 = single.beforeHour==0?1:single.beforeHour;
    }else if (single.beforeHour == 0){
        pos1 = single.beforeDay==0?1:single.beforeDay;
        pos2 = 24;
    }
    NSTimeInterval time = pos1 * pos2 * 60 * 59;//计算给定后的日期
    NSDate * twoDayDate = [NSDate dateWithTimeInterval:time sinceDate:todayDate];//时间间隔
    NSDate * twoDayBeforePayDate = [NSDate dateWithTimeInterval:-(time+24*60*59) sinceDate:payDate];//还款日的前single.beforeDay+1天
    NSDate * twoDayAfterBillDate = [NSDate dateWithTimeInterval:time sinceDate:billDate];//账单日的后single.beforeDay天
    
    if ([[_billDateStr substringWithRange:NSMakeRange(8, 2)] intValue]<[[_payDateStr substringWithRange:NSMakeRange(8, 2)] intValue]) {
        //当月
        if([JNCardSDKMytools compareOneDay:date withAnotherDay:twoDayDate]==1&&[JNCardSDKMytools compareOneDay:twoDayBeforePayDate withAnotherDay:date]==1){
            //日历的日期大于当天日期且小于还款日期，可选
            return [UIColor blackColor];
        }else{//不可选
            return [UIColor colorWithHue:0 saturation:0 brightness:0.67 alpha:1];
        }
    }else{
        //跨月
        if ([JNCardSDKMytools compareOneDay:twoDayDate withAnotherDay:twoDayAfterBillDate]==1) {
            //表示在未跨的那个月，比如账单日7月25，当天7月28，还款8月9
            if ([JNCardSDKMytools compareOneDay:date withAnotherDay:twoDayDate]==1&&[JNCardSDKMytools compareOneDay:twoDayBeforePayDate withAnotherDay:date]==1) {
                return [UIColor blackColor];
            }else{
                return [UIColor colorWithHue:0 saturation:0 brightness:0.67 alpha:1];
            }
        }else{
            if ([JNCardSDKMytools compareOneDay:date withAnotherDay:twoDayBeforePayDate]==1) {
                return [UIColor colorWithHue:0 saturation:0 brightness:0.67 alpha:1];
            }else{
                //因为账单在这个页面一定存在，所以除去上面的那个情况，当天日期一定在8月9之前7月31之后，要做的就是限制8月9之后显示为黑色的bug
                NSInteger  tmpMonth = [[JNCardSDKCalculaterBillPayDay getTheCorrectNum:[_payDateStr substringWithRange:NSMakeRange(5, 2)]] intValue];
                if (tmpMonth == 1) {
                    tmpMonth = 12;
                }else{
                    tmpMonth = tmpMonth - 1;
                }
                NSString * tmpMonthStr = [NSString stringWithFormat:@"%ld",tmpMonth];
                NSString * newPayDateStr = [_payDateStr stringByReplacingCharactersInRange:NSMakeRange(5, 2) withString:tmpMonthStr];
                NSDate * newPayDate  = [JNCardSDKMytools dateStrToDate:newPayDateStr];
                NSDate * twoDayBeforNewPayDate = [NSDate dateWithTimeInterval:-time sinceDate:newPayDate];
                if ([[_billDateStr substringWithRange:NSMakeRange(8, 2)] intValue]<[[_payDateStr substringWithRange:NSMakeRange(8, 2)] intValue]) {
                    if ([JNCardSDKMytools compareOneDay:date withAnotherDay:twoDayDate]==1&&[JNCardSDKMytools compareOneDay:twoDayBeforNewPayDate withAnotherDay:date]==1) {
                        return [UIColor blackColor];
                    }else{
                        return [UIColor colorWithHue:0 saturation:0 brightness:0.67 alpha:1];
                    }
                }else{
                    return [UIColor colorWithHue:0 saturation:0 brightness:0.67 alpha:1];
                }
            }
        }
    }
}
-(void)calendar:(FSCalendar *)calendar didDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    for (NSDate * arrDate in _dateList) {
        if ([arrDate isEqualToDate:date]==YES) {
            [_dateList removeObject:arrDate];
            break;
        }
    }
    date = [date dateByAddingTimeInterval:8 * 60 * 60];
    NSString * sp = [JNCardSDKMytools dateToDateStr:date];
    sp = [sp substringWithRange:NSMakeRange(8, 2)];
    NSString * dateStr = [NSString stringWithFormat:@"[%@日]",sp];
    if ([_hasChoseDateLab.text containsString:dateStr]==YES) {
        _hasChoseDateLab.text = [_hasChoseDateLab.text stringByReplacingOccurrencesOfString:dateStr withString:@""];
    }
    _choseCount --;
}
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    date = [date dateByAddingTimeInterval:8 * 60 * 60];
    NSString * sp = [JNCardSDKMytools dateToDateStr:date];
    sp = [sp substringWithRange:NSMakeRange(8, 2)];
    NSString * dateStr = [NSString stringWithFormat:@"[%@日]",sp];
    _hasChoseDateLab.text = [NSString stringWithFormat:@"%@ %@",_hasChoseDateLab.text,dateStr];
    [_dateList addObject:date];
    _choseCount ++;
}
-(void)resetPlanTime{
    if (_choseCount<_minDays) {
        [JNCardSDKMytools warnText:@"选择天数少于最少可选天数" status:JNCardSDKError];
        return;
    }
    NSMutableArray * tempArr = [NSMutableArray new];
    for (NSDate * aDate in _dateList) {
        [tempArr addObject:[JNCardSDKMytools dateToDateStr:aDate]];
    }
    NSString * urlStr = [JNCardSDKWorkUrl returnURL:Interface_For_ResetPlanTime];
    NSMutableDictionary * paraDic = [JNCardSDKReuserFile returnHYKBaseDic];
    [paraDic setObject:self.planID forKey:@"PlanId"];
    [paraDic setObject:tempArr forKey:@"DateList"];
    [SVProgressHUD show];
    [PGNetworkHelper POST:urlStr parameters:paraDic cache:NO responseCache:nil success:^(id responseObject) {
        [SVProgressHUD dismiss];
        if ([responseObject[@"status"]isEqualToString:@"1"]) {
            [JNCardSDKMytools warnText:responseObject[@"msg"] status:JNCardSDKSuccess];
            dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC);
            dispatch_after(time, dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            if (![responseObject[@"msg"]isEqualToString:@"没有数据"]) {
                [JNCardSDKMytools warnText:responseObject[@"msg"] status:JNCardSDKError];
            }
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
}
@end
